# apps/users/serializers.py
from rest_framework import serializers
from .models import User
from rest_framework.validators import UniqueValidator
import uuid


class UserLoginSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()

    def validate(self, data):
        uname, pwd = data['username'], data['password']

        # admin/admin 快捷通道
        if uname == 'admin' and pwd == 'admin':
            return {"user": {"user_id": "0", "username": "admin",
                             "role": "管理员", "permission_level": 99}}

        # 普通用户：到数据库里查
        try:
            user = User.objects.get(username=uname)
        except User.DoesNotExist:
            raise serializers.ValidationError("用户不存在")

        if user.password != pwd:        # 明文比对（后续请改成加密+check_password）
            raise serializers.ValidationError("密码错误")

        return {"user": user}


class UserInfoSerializer(serializers.Serializer):
    user_id = serializers.CharField()
    username = serializers.CharField()
    role = serializers.CharField()
    permission_level = serializers.IntegerField()


class UserCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['user_id', 'username', 'password', 'email', 'phone', 'role', 'permission_level']
        extra_kwargs = {
            'user_id': {'read_only': True},
            'username': {
                'validators': [UniqueValidator(queryset=User.objects.all())]
            },
            'role': {'default': '普通用户'},
            'permission_level': {'default': 1}
        }

    def create(self, validated_data):
        # 确保有默认角色和权限级别
        validated_data.setdefault('role', '普通用户')
        validated_data.setdefault('permission_level', 1)
        return User.objects.create(**validated_data)

class UserUpdateSerializer(serializers.Serializer):
    password = serializers.CharField(required=False)
    role = serializers.CharField(required=False)
    permission_level = serializers.IntegerField(required=False)
    email             = serializers.EmailField(required=False)
    phone             = serializers.CharField(required=False)

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        return instance


class UserDevicePermissionSerializer(serializers.Serializer):
    user_id = serializers.CharField()
    device_id = serializers.CharField()
    permission = serializers.ChoiceField(choices=["control", "view"])
